package com.puboot.module.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.puboot.common.util.Pagination;
import com.puboot.component.FreeTranslateService;
import com.puboot.component.Json2ClassConvert;
import com.puboot.module.model.LkChapter;
import com.puboot.module.mapper.LkChapterMapper;
import com.puboot.module.model.LkChapterLang;
import com.puboot.module.service.LkChapterLangService;
import com.puboot.module.service.LkChapterService;
import com.puboot.module.vo.ImageDetVo;
import com.puboot.module.vo.ImageRecVo;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.List;


/**
 * (LkChapter)表服务实现类
 *
 * @author Leonidax
 * @since 2024-10-14 11:49:10
 */
@Service
@AllArgsConstructor
public class LkChapterServiceImpl extends ServiceImpl<LkChapterMapper,LkChapter> implements LkChapterService {
    
    private final LkChapterMapper mapper;
    private final FreeTranslateService freeTranslateService;
    private final LkChapterLangService chapterLangService;

    @Override
    public int updateIsFee(Integer id) {
        return mapper.updateIsFee(id);
    }

    @Override
    public int updateTotal(Integer id) {
        return mapper.updateTotal(id);
    }

    @Override
    public List<LkChapter> all4Upload() {
        return mapper.all4Upload();
    }

    @Override
    public HashMap<String, String> getPageInfo(LkChapter chapter, String lang) {
        List<LkChapter> list = chapters(chapter.getComicId(), lang);
        int size = list.size() - 1;
        HashMap<String,String> page = new HashMap<>();
        page.put("firstId",list.get(size).getId().toString());
        Integer nextId = 0;
        Integer prevId = 0;
        for(int i=0; i <= size; i++){
            int currentChapterId = list.get(i).getChapterId();
            if(currentChapterId > chapter.getChapterId()){
                nextId = list.get(i).getId();
            } else if (currentChapterId < chapter.getChapterId()) {
                prevId = list.get(i).getId();
                break;
            }
        }
        if(nextId == 0){
            page.put("nextClass","background:#e0e0e0;");
            page.put("nextUrl","javascript:;");
        }else{
            page.put("nextClass","background:#ff5a49;");
            page.put("nextUrl","/comic/chapter/"+chapter.getComicId()+"/"+nextId);
        }
        if(prevId == 0){
            page.put("prevClass","background:#e0e0e0;");
            page.put("prevUrl","javascript:;");
        }else{
            page.put("prevClass","background:#ff5a49;");
            page.put("prevUrl","/comic/chapter/"+chapter.getComicId()+"/"+prevId);
        }
        return page;
    }

    @Override
    public IPage<LkChapter> check(Integer page) {
        IPage<LkChapter> iPage = new Pagination<>(page,100);
        return mapper.check(iPage);
    }

    private String translateDialog(LkChapter chapter, String lang){
        List<ImageRecVo> recVos = (List<ImageRecVo>) Json2ClassConvert.json2List(chapter.getDialog(), ImageRecVo.class);
        List<ImageDetVo> detVos = (List<ImageDetVo>) Json2ClassConvert.json2List(chapter.getPosition(),ImageDetVo.class);
        StringBuilder content = new StringBuilder();
        int sizeR = recVos.size();
        for(int i=0; i<sizeR; i++){
            if(recVos.get(i) == null) continue;
            int size = recVos.get(i).getL().size();
            for(int j=0; j<size; j++){
                content.append(recVos.get(i).getL().get(j).getW());
                content.append("\n");
            }
        }
        String words;
        if(lang.equals("en")){
            words = content.toString();
        }else{
            words = freeTranslateService.translate(content.toString(),lang);
        }
        String[] lines = words.split("\n");
        int l = 0;
        for(int i=0; i<sizeR; i++){
            if(recVos.get(i) == null) continue;
            int size = recVos.get(i).getL().size();
            for(int j=0; j<size; j++){
                recVos.get(i).getL().get(j).setW(lines[l]);
                int width = detVos.get(i).getL().get(j).getW();
                int height = detVos.get(i).getL().get(j).getH();
                recVos.get(i).getL().get(j).setF(calculateFontSize(lines[l],width,height));
                l++;
            }
        }
        String dialog = Json2ClassConvert.list2Json(recVos);
        LkChapterLang chapterLang = chapterLangService.queryByChapterId(chapter.getId(), lang);
        chapterLang.setDialog(dialog);
        chapterLangService.update(chapterLang);
        return dialog;
    }
    @Override
    public void translateChapter(Integer id, List<ImageRecVo> recVos, List<ImageDetVo> detVos) {
        StringBuilder content = new StringBuilder();
        int sizeR = recVos.size();
        for(int i=0; i<sizeR; i++){
            if(recVos.get(i) == null) continue;
            int size = recVos.get(i).getL().size();
            for(int j=0; j<size; j++){
                content.append(recVos.get(i).getL().get(j).getW());
                content.append("\n");
            }
        }
        if(content.length() == 0) return;
        HashMap<String,String> langs = freeTranslateService.getLangMap();
        for(String lang : langs.keySet()) {
            if(lang.equals("en")) continue;
            LkChapterLang chapterLang = chapterLangService.queryByChapterId(id, lang);
            String words = freeTranslateService.translate(content.toString(),lang);
            //if(chapterLang.getDialog() != null) continue;
            //TODO 有可能524错误，不要try获取异常，保留异常中断
            String[] lines = words.split("\n");
            int l = 0;
            for(int i=0; i<sizeR; i++){
                if(recVos.get(i) == null) continue;
                int size = recVos.get(i).getL().size();
                for(int j=0; j<size; j++){
                    recVos.get(i).getL().get(j).setW(lines[l]);
                    int width = detVos.get(i).getL().get(j).getW();
                    int height = detVos.get(i).getL().get(j).getH();
                    recVos.get(i).getL().get(j).setF(calculateFontSize(lines[l],width,height));
                    l++;
                }
            }
            String dialog = Json2ClassConvert.list2Json(recVos);
            chapterLang.setDialog(dialog);
            chapterLangService.update(chapterLang);
        }
    }

    @Override
    public LkChapter translateChapter(Integer id, String lang) {
        LkChapter chapter = this.getById(id);
        if(chapter.getDialog() == null) return chapter;
        chapter.setDialog(translateDialog(chapter, lang));
        /**
        Thread thread = new Thread(() -> {
            HashMap<String,String> langs = freeTranslateService.getLangMap();
            for(String key : langs.keySet()) {
                LkChapterLang chapterLang = chapterLangService.queryByChapterId(id, key);
                if(chapterLang.getDialog() != null) continue;
                translateDialog(chapter, key);
            }
        });
        thread.start();
         */
        return chapter;
    }

    @Override
    public LkChapter queryById(Integer id, String lang) {
        LkChapter chapter = mapper.queryById(id, lang);
        return chapter;
        /**
        if(chapter.getDialog() != null || lang.equals("en")) return chapter;
        return translateChapter(chapter.getId(),lang);*/
    }

    @Override
    public LkChapter getById(Integer id) {
        return mapper.getById(id);
    }

    @Override
    @Cacheable(value = "chapters", key = "#comicId +':'+ #lang")
    public List<LkChapter> chapters(Integer comicId, String lang) {
        return mapper.chapters(comicId,lang);
    }

    /**
     * 新增数据
     *
     * @param lkChapter 实例对象
     * @return 实例对象
     */
    @Override
    public LkChapter insert(LkChapter lkChapter) {
        this.mapper.save(lkChapter);
        return lkChapter;
    }

    /**
     * 修改数据
     *
     * @param lkChapter 实例对象
     * @return 实例对象
     */
    @Override
    public LkChapter update(LkChapter lkChapter) {
        this.mapper.update(lkChapter);
        return null;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.mapper.deleteById(id) > 0;
    }

    private int calculateFontSize(String text, int width, int height) {
        int size = width*height;
        int fontSize = 50; // 初始较大字体
        BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        Graphics g = img.getGraphics();
        Font font = new Font("Arial", Font.PLAIN, fontSize);
        FontMetrics fm = g.getFontMetrics(font);
        int w = fm.stringWidth(text);
        int h = fm.getHeight();

        // 循环调整字体大小
        while (w*h > size) {
            fontSize--;
            font = new Font("Arial", Font.PLAIN, fontSize);
            fm = g.getFontMetrics(font);
            w = fm.stringWidth(text);
            h = fm.getHeight();
        }
        g.dispose();
        return fontSize;
    }
}
